'use strict';

$(document).ready(function () {
    layui.use(['form', 'element', 'layer', 'jquery', 'laytpl'], function () {

        var form = layui.form(),
            element = layui.element(),
            layer = layui.layer,
            $ = layui.jquery,
            laytpl = layui.laytpl;

        // 自动保存工作总结草稿
        var auto_save_summary = setInterval(function () {
            saveSummary(true);
        }, 120000);

        // +----------------------------------------------------------------------
        // | 渲染评审人模板 - start
        // +----------------------------------------------------------------------

        var SUB_NAME;
        var summary_save_id = null;
        var jump_switch = false; // 附件上传完毕后是否跳转的开关
        var current_page_id;

        var attachmentData = new Array(); //定义存放附件的对象

        // 定义webuploader配置
        var webuploader_option = {
            auto: false,
            server: ThinkPHP['AJAX'] + '/Summary/upload',
            pick: '#filePicker',
            fileVal: 'Filedata',
            accept: {
                title: 'file',
                extensions: 'zip,rar,jpg,png,jpeg,doc,xls,gif,xlsx,docx,pdf,ppt,pptx'
            },
            method: 'POST'
        };

        // 实例化webuploader
        var uploader = WebUploader.create(webuploader_option);

        // 添加到队列时
        uploader.on('fileQueued', function (file) {
            var fileItem = '<div class="file-item" id="' + file.id + '">' + '<div class="pull-left"><i class="file-icon file-icon-ext-' + file.ext + '"></i> ' + file.name + '</div>' + '<div class="pull-right"><i class="icon-remove" title="移除该文件"></i></div>' + '<div class="clearfix"></div>' + '</div>';
            $(webuploader_option.pick).next().append(fileItem);
        });

        // 上传之前
        uploader.on('uploadBeforeSend', function (block, data, headers) {

            data.SUB_NAME = SUB_NAME;
            data.DIR = '/Summary/';
        });

        //上传成功时
        uploader.on('uploadSuccess', function (file, response) {
            //文件了上传成功后触发
            if (response.flag > 0) {
                //当文件上传成功后添加到attachmentData
                attachmentData.push({
                    savename: response.savename,
                    ext: response.ext,
                    path: response.path
                });

                // 文件上传成功后写入数据库
                $.ajax({
                    url: '/Summary/insertAttachment',
                    type: 'POST',
                    data: {
                        SUB_NAME: SUB_NAME,
                        attachments: attachmentData ? JSON.stringify(attachmentData) : null
                    },
                    dataType: 'json',
                    success: function success(response) {
                        if (response.flag > 0) {
                            layer.closeAll();
                            attachmentData = response.data == null ? [] : response.data; // 附件写入后重新覆盖 attachmentData
                            reloadFileQueue(); // 重新渲染附件队列
                            setTimeout(function () {
                                // 如果是自动保存的情况下拒绝跳转
                                if (jump_switch) {
                                    location.href = '/Summary/detail/id/' + SUB_NAME;
                                }
                            }, 2000);
                        } else {
                            layer.closeAll();
                            layer.msg(response.msg, { icon: 2, time: 2000 });
                        }
                    }
                });
            } else {
                layer.closeAll();
                layer.msg(response.msg, { icon: 2, time: 2000 });
            }
        });

        // 所有文件上传结束时
        // uploader.on('uploadFinished', function () {
        //     $.ajax({
        //         url: ThinkPHP['AJAX'] + '/Summary/insertAttachment',
        //         type: 'POST',
        //         data: {
        //             SUB_NAME: SUB_NAME,
        //             attachments: JSON.stringify(attachmentData)
        //         },
        //         dataType: 'json',
        //         success: function (response) {
        //             if (response.flag > 0) {
        //                 layer.closeAll();
        //                 attachmentData = response.data; // 附件写入后重新覆盖 attachmentData
        //                 reloadFileQueue();  // 重新渲染附件队列
        //                 setTimeout(function () {
        //                     if (jump_switch) {
        //                         location.href = 'http://' + ThinkPHP['HTTP_HOST'] + '/Summary/detail/id/' + SUB_NAME;
        //                     }
        //                 }, 2000);
        //             } else {
        //                 layer.closeAll();
        //                 layer.msg(response.msg, {icon: 2, time: 2000});
        //             }
        //         }
        //     });
        // });

        // 上传错误时
        uploader.on('error', function (code) {
            var msg = '';
            switch (code) {
                case 'Q_EXCEED_NUM_LIMIT':
                    msg = '只能上传一个文件';
                    break;
                case 'Q_EXCEED_SIZE_LIMIT':
                    msg = '文件大小超出限制';
                    break;
                case 'Q_TYPE_DENIED':
                    msg = '文件格式不允许';
                    break;
                case 'F_DUPLICATE':
                    msg = '文件已存在';
                    break;
                default:
                    msg = code;
            }
            layer.msg(msg, { icon: 2, time: 2000 });
        });

        // 删除队列文件
        // $('.uploader-file-queue').on('click', '.icon-remove', function () {
        //     // 如果删除按钮包含了 'remove-attachment-btn' 该class名则说明是编辑页面，并且包含附件，该操作为删除数据库里面的数据且删除服务器真实文件
        //     if ($(this).hasClass('remove-attachment-btn')) {
        //         let _parent = $(this).parent().parent();
        //         let id = $(this).attr('sample-id');
        //         let key = $(this).attr('key');
        //         $.post('/sample/destroyAttachment', {
        //             id, key
        //         }, function (response) {
        //             if (response.errcode) {
        //                 layer.msg(response.msg, {icon: 2, time: 1500});
        //                 setTimeout(function () {
        //                     layer.closeAll();
        //                 }, 1500);
        //             } else {
        //                 _parent.remove();
        //             }
        //         });
        //     } else {
        //         var id = $(this).parent().parent().attr('id');
        //         // 删除队列中的文件
        //         uploader.removeFile(uploader.getFile(id, true));
        //         // 删除dom节点
        //         $(this).parent().parent().remove();
        //     }
        // });

        $('.uploader-file-queue').on('click', '.icon-remove', function () {
            var path = $(this).attr('data-path');
            var _id = $(this).attr('data-id');
            var _this = $(this);
            // 如果标签存在 data-path 说明该文件属于服务器真实文件，反之则为本地队列里的文件
            if (path) {
                console.log('server file.');
                removeServerFile({ path: path, id: _id }).then(function (response) {
                    if (response.errno) {
                        layer.msg(response.message, { icon: 2, time: 3000 });
                    } else {
                        attachmentData = response.data == null ? [] : response.data;
                        // 删除 dom 节点
                        _this.parent().parent().remove();
                        reloadFileQueue();
                    }
                });
            } else {
                var id = $(this).parent().parent().attr('id');
                // 删除队列中的文件
                uploader.removeFile(id, true);
                // 删除dom 节点
                $(this).parent().parent().remove();
            }
        });

        function removeServerFile(data) {
            return new Promise(function (resolve, reject) {
                $.post('/Summary/removeFile', data, function (response) {
                    resolve(response);
                }, 'json');
            });
        }

        var fields = void 0;

        // 渲染到模板中的数据
        var data = {
            auditID: 'Audit',
            ccID: 'Cc',
            title: '',
            attachment: [],
            selected: [], // 选中的评审人
            cc_selected: [], // 选中的抄送人
            result: null
        };

        // 类型监听
        form.on('select(type)', function (data) {
            if (data.value == 'summary') {
                $('.week-resource-box').css('display', 'none');
                $('.week-summary').css('display', 'block');
            } else {
                $('.week-summary').css('display', 'none');
                $('.week-resource-box').css('display', 'block');
            }
        });

        // 项目监听
        form.on('select(resource_sort)', function (data) {
            if (data.value != '1') {
                $(this).parents('.week-resource').find('.project-number').css('display', 'none');
            } else {
                $(this).parents('.week-resource').find('.project-number').css('display', 'block');
            }
        });

        // 资源分类json转换成对象
        resource = eval('(' + resource + ')');

        // 项目分类json转换成对象
        project = eval('(' + project + ')');

        // 点击添加一列资源选项
        $('.add-result').click(function () {
            var _html = '<div class="week-resource">' + '<div class="row" style="height: 60px;">' + '<div class="close-resource" title="移除"><i class="icon-remove"></i></div>' + '<div class=" resource_sort_pra pull-left col-md-7" >' + '<label class="layui-form-label">工作类型</label><div class="layui-input-block">' + '<select name="resource_sort" lay-filter="resource_sort">';
            for (var item in resource) {
                _html += '<option value="' + resource[item].id + '">' + resource[item].name + '</option>';
            }
            _html += '</select></div></div>' + '<div class="pull-left col-md-5"><label class="layui-form-label">工作耗时</label>' + '<div class="layui-input-block" ><input type="number" name="project_scale" required lay-verify="required" required placeholder="工作耗时(天数)" autocomplete="off" class="layui-input project_scale">' + '</div></div></div>';
            _html += '<div class=" project-number" style="margin: 0 0 25px 0;">' + '<label class="layui-form-label">项目名称</label>' + '<div class="layui-input-block" ><select name="project_sort" lay-filter="required">';
            for (var item in project) {
                _html += '<option value="' + project[item].id + '">' + project[item].pj_num + '（' + project[item].pj_name + '）</option>';
            }
            _html += '<option value="0">其它项目</option>';
            _html += '</select></div></div> ' + '<div class="layui-form-item"><label class="layui-form-label">工作内容</label>' + '<div class="layui-input-block" ><textarea style="height: 150px;" name="project_info" required placeholder="详细工作内容" class="layui-textarea"></textarea></div>' + '</div>' + '</div>';
            $('.html-content').append(_html);
            form.render();
        });

        // 点击移除一列资源选项
        $(document).on('click', '.close-resource', function () {
            $(this).parents('.week-resource').remove();
        });

        // +----------------------------------------------------------------------
        // | 渲染评审人模板 - end
        // +----------------------------------------------------------------------

        // 确认发布
        $('#submit-discuss-content').click(function (datas) {
            // 手动点击保存后关闭自动保存
            clearInterval(auto_save_summary);
            // 收集表单数据
            var result = collectFormData(true, true);
            // 如果 result 是字符串类型则说明验证失败，值为错误描述
            if (typeof result == 'string') {
                layer.msg(result, { icon: 2, time: 3000 });
                return;
            }
            // 将发布标记置为 1
            result.is_publish = 1;
            // 如果存在自动保存的记录则将 id 附在 formData 中
            if (summary_save_id) result.id = summary_save_id;
            // 展开 loading 层
            var index = layer.load(2, {
                shade: [0.5, '#fff'] // 0.5 透明度的白色背景
            });
            // 提交数据和处理附件相关
            publishOrSaveSummary(result).then(function (response) {
                if (response.flag > 0) {
                    // SUB_NAME 为总结 id，上传附件时携带
                    SUB_NAME = response.flag;
                    if (uploader.getFiles().length > 0) {
                        // 如果是保存则将跳转开关打开
                        jump_switch = true;
                        uploader.upload();
                    } else {
                        location.href = '/Summary/detail/id/' + response.id;
                    }
                } else {
                    layer.msg(response.msg, { icon: 2, time: 2000 });
                    setTimeout(function () {
                        layer.closeAll();
                    }, 2000);
                }
            });

            return false;
        });

        function publishOrSaveSummary(data) {
            return new Promise(function (resolve, reject) {
                $.ajax({
                    url: '/Summary/add',
                    data: data,
                    type: 'POST',
                    dataType: 'json',
                    success: function success(response) {
                        resolve(response);
                    }

                });
            });
        }

        function collectFormData() {
            var is_verify = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
            var is_auto_save = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
            var cc = data.cc_selected;

            if ($('.type-d select').val() == 'summary') {
                console.log('type: summary');
                // 判断是否输入的空格 回车 空
                var strValue = editor.txt.text();
                var string = strValue.replace(/\&nbsp\;/ig, ' ');

                if (is_verify) {
                    if (!$.trim(string).length) {
                        return '本周总结不能为空';
                    }

                    var strVal = $('textarea[name=next-week]').val();
                    if ($.trim(strVal) == "") {
                        return '下周任务不能为空';
                    }
                }

                // 拼装提交数据
                var result = new Object();
                result.type = $('.type-d select').val();
                result.content = editor.txt.html();
                result.next_week = $(' textarea[name=next-week] ').val();
                result.other = $(' textarea[name=other] ').val();
                result.uid = $('.push-person').attr('uid');
                result.title = $('.title').val();
                result.cc = cc;
                result.attachment = attachmentData;
                result.week = getWeekOfYear();
            } else {
                console.log('type: resource');
                var result = new Object();
                var arr = new Array();
                var nr_valid = true;
                var hs_valid = true;
                var tmpStr = '';
                $('.week-resource').each(function (evt) {
                    var tmpArr = new Object();
                    tmpArr.resource_sort = $(this).find(' select[name = resource_sort]').val();
                    if ($(this).find(' select[name = resource_sort]').val() == 1) {
                        tmpArr.project_sort = $(this).find(' select[name = project_sort]').val();
                    }
                    tmpArr.project_info = $(this).find(' textarea[name = project_info]').val();
                    tmpArr.project_scale = $(this).find(' input[name = project_scale]').val();

                    var strValue = $(this).find(' textarea[name = project_info]').val();
                    arr.push(tmpArr);
                    if ($.trim(strValue) == "") {
                        nr_valid = false;
                        tmpStr = '工作内容不能为空';
                        return false;
                    }
                    if ($(this).find('input[name = project_scale]').val() == '') {
                        hs_valid = false;
                        tmpStr = '工作耗时不能为空';
                        return false;
                    }
                });
                if (nr_valid === false) return tmpStr;
                if (hs_valid === false) return tmpStr;
                var strVal = $('textarea[name=next-week]').val();
                if ($.trim(strVal) == "") {
                    return '下周任务不能为空';
                }
                result.resource = arr;
                result.next_week = $('textarea[ name = next-week ]').val();
                result.other = $('textarea[ name = other ]').val();
                result.title = $('.title').val();
                result.cc = cc;
                result.attachment = attachmentData;
                result.type = $('.type-d select').val();
                result.uid = $('.push-person').attr('uid');
                result.week = getWeekOfYear();
            }

            return result;
        }

        function reloadFileQueue() {
            var file_queue = '';
            for (var item in attachmentData) {
                file_queue += '<div class="file-item clearfix">\n                                <div class="pull-left">\n                                    <i class="file-icon file-icon-ext-' + attachmentData[item].ext + '"></i>\n                                    ' + attachmentData[item].savename + '\n                                </div>\n                                <div class="pull-right">\n                                    <i class="icon-remove" data-path="' + attachmentData[item].path + '" data-id="' + current_page_id + '" title="\u79FB\u9664\u8BE5\u6587\u4EF6"></i>\n                                </div>\n                            </div>';
            }
            $('.uploader-file-queue').html(file_queue);
        }

        // 获取指定时间年份和周数
        var myDate = new Date();

        $('.title').val(myDate.getFullYear() + '年第' + getWeekOfYear() + '周工作总结');

        function getWeekOfYear() {
            var today = new Date();
            var firstDay = new Date(today.getFullYear(), 0, 1);
            var dayOfWeek = firstDay.getDay();
            var spendDay = 1;
            if (dayOfWeek != 0) {
                spendDay = 7 - dayOfWeek + 1;
            }
            firstDay = new Date(today.getFullYear(), 0, 1 + spendDay);
            var d = Math.ceil((today.valueOf() - firstDay.valueOf()) / 86400000);
            var result = Math.ceil(d / 7);
            return result + 1;
        };

        // 保存为草稿
        $('#save-draft').click(function () {
            clearInterval(auto_save_summary);
            saveSummary(true, false);
        });

        function saveSummary() {
            var is_verify = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
            var is_auto_save = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

            var data = collectFormData(is_verify, false);
            // 自动保存也开启验证，如果验证失败则不进行本次保存
            // 如果 result 是字符串类型则说明验证失败，值为错误描述
            if (typeof data == 'string') {
                // 如果手动点击保存草稿验证错误给与提示
                if (!is_auto_save) {
                    layer.msg(data, { icon: 2, time: 3000 });
                }
                return;
            }
            // 新增标识
            data.add_flag = true;
            // 将发布标记置为 0
            data.is_publish = 0;
            // 如果自动保存成功后将 id 记录下来并提交
            if (summary_save_id) data.id = summary_save_id;
            // 如果不是自动保存将 data.id 删除并清除自动保存
            // if (!is_auto_save) {
            //     // delete data.id;
            //     // 如果不是自动保存则展开 loading 弹层
            //     let _loading = layer.load(1, {
            //         shade: [0.5, '#fff']
            //     });
            // }
            if (is_auto_save) {
                $('#save-draft').text('自动保存中...').addClass('layui-btn-disabled');
            } else {
                $('#save-draft').text('正在保存...').addClass('layui-btn-disabled');
            }
            publishOrSaveSummary(data).then(function (response) {
                if (response.flag > 0) {
                    $('#save-draft').text('保存草稿').removeClass('layui-btn-disabled');
                    // layer.closeAll();
                    SUB_NAME = response.flag;
                    current_page_id = response.id;
                    // 如果有返回 id 则替换 summary_save_id
                    if (response.id) summary_save_id = response.id;
                    // 提示文本
                    var save_msg = is_auto_save ? '已自动保存' : '已保存至草稿箱';

                    // 检查队列中是否存在文件，如果存在则上传
                    if (uploader.getFiles().length > 0) {
                        uploader.upload();
                    }

                    layer.msg(response.msg, {
                        offset: '80px',
                        icon: 1,
                        content: '<p>' + save_msg + '\uFF0C<a class="txt-primary" href="' + response.url + '">\u70B9\u51FB\u6B64\u5904\u67E5\u770B</a></p>',
                        time: 5000
                    });
                } else {
                    layer.msg(response.msg, { icon: 2, time: 2000 });
                    setTimeout(function () {
                        layer.closeAll();
                    }, 2000);
                }
            });
        }
    });
});